<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
    public $components = array(
        'Session',
        'Cookie',
        'Auth' => array(
            'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home') ,
            //'authorize' => array('Controller') // Added this line
        )
    );
    public $uses = array('User','Order');
    //public $uses=array('User','Order','Publicpage');
    public function beforeFilter() {
        //$this->Auth->allow('index', 'posts'); //То, что юзер видит без логина
        $this->Auth->allow('posts','view','forgetpass','captcha','paysuccess','payfail','payresult');
        $cookie = array();
        $cookie = $this->Cookie->read('User');
        $userid=@$cookie['id'];
        $passhash=@$cookie['password'];
        if (is_array($cookie) && !$this->Auth->user())
        {
          if ($this->checkLogin($userid, $passhash))
          {
            if ($this->Auth->login($cookie))
            {
              //$this->redirect($this->Auth->redirect());
              $this->redirect(array('controller'=>'pages','action' => 'index'));
            }
          }
        }
        $userid= $this->Auth->User('id');
        if($userid>0)
        {
          $orders=$this->Order->findAllByUserid($userid);
          $this->set('orders_for_autodj',@$orders);
          //$this->set('title_for_layout', 'Админцентр: управление заказами');
          $this->set('user_name_sidebar', AppController::getUserName($userid));
        }
        if (isset($this->request->params['admin']))
        {
          if(!$this->isAuthorized($userid))
          {
            //$this->redirect(array('controller'=>'pages','action' => 'index'));
            $this->redirect('/');
          }
        }
        /*echo '<pre>';
        print_r($cookie);
        echo '</pre>'; */

    }
    public function isAuthorized($userid) {
      //$userid= $this->Auth->User('id');
      $user_data=$this->User->findById($userid);
      // Admin can access every action
      if (isset($user_data['User']['role']) && $user_data['User']['role'] == 10) {
          return true;
      }
      // Default deny
      return false;
    }
    public function isReseller($userid) {
      //$userid= $this->Auth->User('id');
      $user_data=$this->User->findById($userid);
      // Admin can access every action
      if (isset($user_data['User']['role']) && $user_data['User']['role'] > 0) {
          return true;
      }
      // Default deny
      return false;
    }
    public function EncryptPassword($content)
    {
      include_once('../AES.class.php');
      $key256 = 'l;05db1015bcldse2b73aef0857d77811f352c073b6108d72d9810a3091hylad';
      $Cipher = new AES(AES::AES256);
      $content = $Cipher->stringToHex($content);
      $content = $Cipher->encrypt($content, $key256);
      return $content;
    }
    public function DecryptPassword($content)
    {
      include_once('../AES.class.php');
      $key256 = 'l;05db1015bcldse2b73aef0857d77811f352c073b6108d72d9810a3091hylad';
      $Cipher = new AES(AES::AES256);
      $content = $Cipher->decrypt($content, $key256);
      $content = $Cipher->hexToString($content);
      return $content;
    }
    public function _is_curl_installed() {
      if  (in_array  ('curl', get_loaded_extensions())) {
          return true;
      }
      else {
          return false;
      }
  }
  public function translitIt($str)
  {
      $tr = array(
          "А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
          "Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
          "Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
          "О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
          "У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
          "Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
          "Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
          "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
          "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
          "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
          "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
          "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
          "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya",
          " "=> "_", "."=> ""
      );
      return strtr($str,$tr);
  }
  public function xss($var){
      if(is_array($var)) {
          foreach($var as $k=>$v)
              $new[$k] = xss($v);
          return $new;
      }
      return htmlspecialchars(strip_tags($var));
  }
    public function getbalance($userid){
      $query = "SELECT * FROM `balance` WHERE `userid`='$userid' LIMIT 1";
      $balace_data=$this->Order->query($query);
      $balance=round(@$balace_data[0]['balance']['balance'],2);
       $time=@$balace_data[0]['balance']['time'];
       if($balance=="")
          $balance=0;
       if($time==0)
          $time="Нет";
       else
          $time=date("H:i d.m.Y",$time);
      $balance_arr=array('balance' => $balance, 'time' =>$time);
      return $balance_arr;
    }
    public function getUserName($userid)
    {
      $data=$this->User->findById($userid);
      $name= $data['User']['name'];
      if($name=='')
        $name=$data['User']['login'];
      return $name;
    }
    public function getUserLogin($userid)
    {
      $data=$this->User->findById($userid);
      $name=$data['User']['login'];
      return $name;
    }
    public function getUserEmail($userid)
    {
      $data=$this->User->findById($userid);
      $name=$data['User']['email'];
      return $name;
    }
    public function checklogin($userid,$passhash){
      $user = $this->User->findByIdAndPassword($userid,$passhash);
      if($user)
        return true;
      else
       return false;
    }
    public function edit_user_hid($root, $rootpass, $hid_user,$hid_password,$preset){
        $url = "https://".$_SERVER['SERVER_ADDR']."/manager/ispmgr?authinfo=".$root.":".$rootpass."&out=xml&func=user.edit";
        $add_user["sok"] = "yes";
        $add_user["elid"] = $hid_user;
        $add_user["name"] = $hid_user;
        $add_user["passwd"] = $hid_password;
        $add_user["confirm"] = $hid_password;
        #$add_user["owner"] = $hid_user;
        #$add_user["ip"] = $_SERVER['SERVER_ADDR'];
        #$add_user["ip6"] = "";
        #$add_user["domain"] = $domain;
        $add_user["preset"] = $preset; // Shablon user hosting
        #$add_user["email"] = $hid_email;
        #$add_user["welcome"] = "on"  ;
        #$add_user["shell"] = "on" ;
        #$add_user["ssl"] = ;
        #$add_user["cgi"] = "on";
        #$add_user["wsgi"] = WSGI. ;
        #$add_user["ssi"] = SSI.;
        $add_user["phpmod"] ='on';
        #$add_user["phpcgi"] =;
        #$add_user["phpfcgi"] =  "on";
        #$add_user["safemode"] =  ;
        switch($preset)
        {
          case 'Extra1':$bandwidth=2000; break;
          case 'Extra2':$bandwidth=4000; break;
          case 'Extra3':$bandwidth=10000; break;
        }
        $add_user["disklimit"] = $bandwidth; # в Мегабайтах
        #$add_user["ftplimit"] ="10000";
        #$add_user["maillimit"] = "10000";
        #$add_user["domainlimit"] = "10000";
        #$add_user["webdomainlimit"] = "10000";
        #$add_user["maildomainlimit"] = "10000";
        #$add_user["baselimit"] = "10000";
        #$add_user["baseuserlimit"] = "10000";
        #$add_user["bandwidthlimit"] = "100000000";
        #$add_user["cpulimit"] = "100000";
        #$add_user["memlimit"] = "100000";
        #$add_user["proclimit"] = "100000";
        #$add_user["mysqlquerieslimit"] = "100000000";
        #$add_user["mysqlupdateslimit"] = "100000000";
        #$add_user["mysqlconnectlimit"] = "100000000";
        #$add_user["mysqluserconnectlimit"] = "100000000";
        #$add_user["maxclientsvhost"] = "100000000";
        #$add_user["mailrate"] = "100000000";
        #$add_user["note"] = "";

         foreach( $add_user as $k => $v )
           {
             $url .= '&'.$k.'='.urlencode($v);
         }
        echo $url;
        // exit();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Get the response and close the channel.
        $response = curl_exec($ch);
        curl_close($ch);
        $findme="<doc><ok/></doc>";
        $pos = strpos($response, $findme);
        if($pos === false)
        {
          return 0;
        }
        else
        {
          return 1;
        }
    }
    public function send_email($email,$title,$message,$headers)
    {
      $mail_content='
    <div class="rh_mail_wrapper" style="width:100%;font-family: \'Tahoma\', sans-serif;">
        <div class="rh_mail_header" style="border-bottom: 1px solid  #d4d4d4;padding-bottom:10px;">
            <table width="100%">
                <tr>
                    <td width="50">
                        <img src="http://radioheart.ru/rh_mail_template/heart_nolsd.png" />
                    </td>
                    <td align="right">
                        <a href="http://radioheart.ru" target="_blank" style="color:#4d8dae;font-size:12px;text-decoration:none;margin-left:10px;">radioheart.ru</a>
                        <a href="http://radioheart.ru/billing" style="color:#4d8dae;font-size:12px;text-decoration:none;margin-left:10px;" target="_blank">биллинг</a>
                    </td>
                </tr>
            </table>
        </div>
        <div class="rh_mail_content" style="font-size:14px;color:#000000;margin-top:30px;border-bottom: 1px solid  #d4d4d4;padding-bottom:10px;">
            Уважаемый клиент!<br />
            '.$message.'
            <div class="rh_mail_go_to_billink_lnk" style="margin-top:15px;">
                <a href="http://radioheart.ru/billing" target="_blank" style="color:#4d8dae;font-size:16px;text-decoration:none;">Перейти в биллинг</a>
            </div>
        </div>
        <div class="rh_mail_footer" style="font-size:12px;color:#8e8e8e;margin-top:15px;">
            <table width="100%">
                <tr>
                    <td>
                        Это письмо отправлено автоматически. Но вы можете задать нам вопрос, ответив на него.
                    </td>
                    <td align="right">
                        <a href="http://vk.com/radiohearthost" target="_blank"><img src="http://radioheart.ru/rh_mail_template/vk.png" style="border:none;"/></a>
                        <a href="https://www.facebook.com/radioheartru" target="_blank"><img src="http://radioheart.ru/rh_mail_template/fb.png" style="border:none;"/></a>
                        <a href="https://twitter.com/radioheartru" target="_blank"><img src="http://radioheart.ru/rh_mail_template/tw.png" style="border:none;"/></a>
                    </td>
                </tr>
            </table>
        </div>
    </div>
      ';
      mail($email,$title,$mail_content,$headers);
      return 1;
    }
    public function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}
